package com.swordxu.yim.server.packet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.swordxu.yim.server.dbproxy.model.Department;
import com.swordxu.yim.server.packet.base.DefaultHeader;
import com.swordxu.yim.server.packet.base.Header;
import com.swordxu.yim.server.packet.base.Packet;
import com.swordxu.yim.server.utils.ProtocolConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门数据包
 * Created by 徐晓明 on 2015/1/13.
 */
public class DepartmentPacket extends Packet {

    public DepartmentPacket() {
        mRequest = new PacketRequest();
    }

    /**
     * 封包方法
     * @return
     */
    @Override
    public String encode() {
        Header header = mResponse.getHeader();
        PacketResponse res = (PacketResponse) mResponse;
        JSONObject jo = new JSONObject();
        jo.put("header", header);
        JSONArray ja = new JSONArray();
        List<Department> list = res.getEntityList();
        for (Department dp : list) {
            ja.add(dp.toJson());
        }
        jo.put("body", ja);
        return jo.toJSONString();
    }

    /**
     * 解包方法
     * @param buffer
     */
    @Override
    public void decode(String buffer) {
        PacketRequest rq = new PacketRequest();
        Header header = new Header();
        JSONObject jo = JSON.parseObject(buffer);
        header = jo.getObject("header", Header.class);
        rq.setHeader(header);
        this.mRequest = rq;
    }

    /**
     * 请求数据包
     */
    public static class PacketRequest extends Request {

    }

    /**
     * 响应数据包
     */
    public static class PacketResponse extends Response {
        public List<Department> entityList = new ArrayList<Department>();

        public PacketResponse() {
            Header header = new DefaultHeader(ProtocolConstant.SID_BUDDY_LIST,
                    ProtocolConstant.CID_BUDDY_LIST_DEPARTMENT_RESPONSE);

            setHeader(header);
        }

        public PacketResponse( List<Department> entityList) {
            Header header = new DefaultHeader(ProtocolConstant.SID_BUDDY_LIST,
                    ProtocolConstant.CID_BUDDY_LIST_DEPARTMENT_RESPONSE);
            setEntityList(entityList);
            setHeader(header);
        }

        public void setEntityList(List<Department> list) {
            this.entityList = list;
        }

        public List<Department> getEntityList() {
            return entityList;
        }
    }
}
